import * as vscode from "vscode";
import type { CompletionItem, CompletionItemProvider } from "vscode";
import { colors } from "./colors";
import { validatorColorDocument } from "./Validator";

export function registerColorCompletionItemProvider(context: vscode.ExtensionContext) {
  const colorsProvider = vscode.languages.registerCompletionItemProvider("传奇脚本", ColorCompletionItemProvider, "=");
  context.subscriptions.push(colorsProvider);

  // 注册触发命令
  const triggerCommand = vscode.commands.registerCommand("mir-script-extension.showColorPicker", () => {
    global.isCommandTriggered = true;
    // 执行两步操作：
    vscode.commands.executeCommand("editor.action.triggerSuggest").then(() => {
      // 重置状态（延迟确保补全列表弹出）
      setTimeout(() => (global.isCommandTriggered = false), 500);
    });
  });
  context.subscriptions.push(colorsProvider, triggerCommand);
}

export const ColorCompletionItemProvider: CompletionItemProvider = {
  provideCompletionItems(document, position) {
    const linePrefix = document.lineAt(position).text.slice(0, position.character);

    if (!validatorColorDocument(linePrefix) && !global.isCommandTriggered) {
      return undefined;
    }

    const list: CompletionItem[] = [];
    colors.forEach((color) => {
      list.push({
        detail: `${color.hex}`,
        documentation: color.number,
        kind: vscode.CompletionItemKind.Color,
        filterText: color.number,
        label: `${color.number}`,
        insertText: color.number,
      });
    });
    return list;
  },
};
